package cn.tanghom.app.oa.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.TextCriteria;
import org.springframework.data.mongodb.core.query.TextQuery;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mongodb.BasicDBObject;
import com.unbiz.common.StringUtil;

import cn.tanghom.content.model.Accessory;
import cn.tanghom.content.model.Article;
import cn.tanghom.content.model.ArticleCategory;
import cn.tanghom.content.service.ArticleCategoryService;
import cn.tanghom.content.service.ArticleService;
import cn.tanghom.app.oa.model.Talent;
import cn.tanghom.app.oa.repository.EduExpRepository;
import cn.tanghom.app.oa.repository.ProjectExpRepository;
import cn.tanghom.app.oa.repository.TalentRepository;
import cn.tanghom.app.oa.repository.WorkExpRepository;
import cn.tanghom.conf.CommonKey;
import cn.tanghom.support.id.IDWorker;
import cn.tanghom.support.page.Pager;
import cn.tanghom.support.utils.CommonUtils;
import cn.tanghom.support.utils.StringUtils;
import static cn.tanghom.support.web.BaseController.THEME_PATH;
/**
 * 简历解析，人才管理, 
 * 
 * 文本简历的model为Article，人才的model为Resume
 * @author Hunteron-cp
 *
 */
@Controller
@RequestMapping("/oa/talent")
public class TalentController {
	
	final Long talentCategoryId = 8L;
	String collection = "hd_talent_resume_receive";
	
	IDWorker resumeIdSeq = new IDWorker(1,talentCategoryId);;
	
	@Autowired
	private MongoOperations destination;
	
	@Resource
    private ArticleCategoryService articleCategoryService;
	
	@Resource 
	private ArticleService articleService;
	
	@Autowired
	TalentRepository talentRepository;
	
	@Autowired
	WorkExpRepository workExpRepository;
	
	@Autowired
	EduExpRepository eduExpRepository;
	
	@Autowired
	ProjectExpRepository projectExpRepository;

    /**
     * 列表
     *
     * @param categoryId
     * @param status
     * @param model
     * @return
     */
    @RequestMapping(value = "/list", method = {RequestMethod.POST, RequestMethod.GET})
    public String list(String title, Long categoryId, Integer status, Long pageNo, Model model) {
        status = status == null || status < 0 ? null : status;
        categoryId = categoryId == null || categoryId < 0 ? null : categoryId;
        int pageIndex = pageNo!=null? pageNo.intValue():0;
        PageRequest pager = new PageRequest(pageIndex,20);
        Page<Talent> page;
        
    	if(title!=null && title.length()>0){
    		page = talentRepository.queryFirst10ByName(title, pager);
    	}
    	else if(categoryId!=null){
        	page = talentRepository.findByLevel(categoryId.intValue(), pager);
        }
    	else if(status!=null){
        	page = talentRepository.findByStatus(status, pager);
        }
    	else{       
    		page = talentRepository.findAll(pager);
    	}
        model.addAttribute("page", page);
        model.addAttribute("pageIndex",pageIndex);
        List<ArticleCategory> articleCategoryList = articleCategoryService.findListByParentId(talentCategoryId, 1);
        model.addAttribute("articleCategoryList", articleCategoryList);
        return THEME_PATH + "/oa/talent/list";
    }
    

    /**
     * 显示在线简历页面
     *
     * @return
     */
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String view(Long id, Model model) {
    	Talent resume = talentRepository.findById(id);
    	if(resume==null){
    		throw new RuntimeException("找不到简历，可能是简历还没有解析完成。");
    	}
    	Article article = null;
    	if(resume.getHtmlContentId()!=null){
	    	 model.addAttribute("format", "html");   
	    	 article= articleService.findById(resume.getHtmlContentId());
	    	
	     }
	     else if(resume.getTextContentId()!=null){
	    	 model.addAttribute("format", "text");
	    	 article= articleService.findById(resume.getTextContentId());
	     }
       
        model.addAttribute("article", article);
        model.addAttribute("talent", resume);
        
        List<Talent.WorkExp> works = workExpRepository.findByResumeId(resume.getResumeId());
        model.addAttribute("works", works);        
        
        List<Talent.EduExp> edus = eduExpRepository.findByResumeId(resume.getResumeId());
        model.addAttribute("edus", edus);
        
        List<Talent.ProjectExp> projects = projectExpRepository.findByResumeId(resume.getResumeId());
        model.addAttribute("projects", projects);
        
        List<ArticleCategory> articleCategoryList = articleCategoryService.findListByParentId(talentCategoryId, 1);
        model.addAttribute("articleCategoryList", articleCategoryList);
        return THEME_PATH + "/oa/talent/view";
    }

    /**
     * 显示html文章页面
     * @parma id resumeId
     * @return
     */
    @RequestMapping(value = "/html", method = RequestMethod.GET)
    @ResponseBody
    public String html(Long id, Model model) {
    	Talent resume = talentRepository.findById(id);
    	Article article = null;
	     
	     if(resume.getHtmlContentId()!=null){
	    	 model.addAttribute("format", "html");   
	    	 article= articleService.findById(resume.getHtmlContentId());
	    	
	     }
	     else if(resume.getTextContentId()!=null){
	    	 model.addAttribute("format", "text");
	    	 article= articleService.findById(resume.getTextContentId());
	     }
	     
	    String html = article.getContent();
     	if(html==null || html.isEmpty()){
     		html ="<pre>\n"+"no html content."+"\n</pre>";
     	}    
    	    
        return html;
    }
    
    /**
     * 显示text文章页面
     *
     * @return
     */
    @RequestMapping(value = "/text", method = RequestMethod.GET)  
    public String text(Long id, Model model) {
    	Talent resume = talentRepository.findById(id);
    	Article article = null;	     
	     
	     if(resume.getTextContentId()!=null){
	    	 model.addAttribute("format", "text");
	    	 article= articleService.findById(resume.getTextContentId());
	     }
	     else if(resume.getHtmlContentId()!=null){
	    	 model.addAttribute("format", "html");   
	    	 article= articleService.findById(resume.getHtmlContentId());	    	
	     }	     
	   
    	String content = article.getContent();
    	if(content==null || content.isEmpty()){
    		content ="<pre>\n"+"no text content."+"\n</pre>";
    	}    
    	model.addAttribute("article", article);
    	return THEME_PATH + "/oa/talent/article_view";
    }
    
    /**
     * 解析简历
     *
     * @param categoryId
     * @param status
     * @param model
     * @return
     */
    @RequestMapping(value = "/parse", method = {RequestMethod.GET})
    public String parseReq(Long id,Model model) {
    	Talent resume =  null;
    	if(id!=null){
    		 resume = talentRepository.findById(id);
    		 model.addAttribute("resumeId", id);   
    		 
    	     Article article = null;
    	     
    	     if(resume.getHtmlContentId()!=null){
    	    	 model.addAttribute("format", "html");   
    	    	 article= articleService.findById(resume.getHtmlContentId());
    	     }
    	     else if(resume.getTextContentId()!=null){
    	    	 model.addAttribute("format", "text");
    	    	 article= articleService.findById(resume.getTextContentId());
    	     }
    	     model.addAttribute("article", article);
    	}
       
        List<ArticleCategory> articleCategoryList = articleCategoryService.findListByParentId(talentCategoryId, 1);
        model.addAttribute("articleCategoryList", articleCategoryList);
        return THEME_PATH + "/oa/talent/input";
    }
    
    /**
     * 解析简历,保存到Article里面
     *
     * @Long resume_id 简历ID
     * @param categoryId
     * @param status
     * @param model
     * @return
     */
    @RequestMapping(value = "/parse", method = {RequestMethod.POST})
    @ResponseBody
    public String parseReq(@RequestParam(value="resumeId") Long resume_id,Long categoryId, Article model) {
    	resume_id = resume_id == null || resume_id < 0 ? null : resume_id;
        categoryId = categoryId == null || categoryId < 0 ? null : categoryId;
      
        Talent resume = null;
        if(resume_id==null){
        	resume_id = resumeIdSeq.nextId();
        }
        else{
        	resume = talentRepository.findById(resume_id);
        	if(resume!=null){
        		throw new RuntimeException("找不到简历，可能是简历已经删除。");
        	} 
        }
    	   
    	BasicDBObject doc = new BasicDBObject();
    	doc.append("resume_id", resume_id);
    	doc.append("status", 0);
    	String content = model.getContent();
    	content = content.trim();
    	if(model.getFormat()==null){
    		if(content.startsWith("<html") || content.startsWith("<body") || content.startsWith("<!DOCTYPE")){
				doc.append("htm_content", content);
				doc.append("format", "html");
				model.setFormat("html");
			}
			else{
				doc.append("txt_content", content);
				doc.append("format", "text");
				model.setFormat("text");
			}
    	}
    	else{
    		if(model.getFormat().equals("html")){
    			doc.append("htm_content", content);
				doc.append("format", "html");
    		}
    		else{
    			doc.append("txt_content", content);
				doc.append("format", "text");
    		}    		
    	}    	
    	
    	articleService.saveOrUpdate(model);
    	
    	if(resume!=null){			
			doc.append("fullName", resume.user_key);
			doc.append("categoryId", resume.categoryId);
		}
    	
    	try{
    		
    		if(StringUtil.isEmpty(content) || content.length()<256){
    			if(resume!=null){
    				
    			}
    			else{
    				return CommonUtils.msgCallback(false, "操作失败，resumeId和文本至少填写一个！", "", null);
    			}
    		}
    		
    		destination.save(doc,collection);
    		
    		return CommonUtils.msgCallback(true, "解析请求发送成功,请等待结果。", "/oa/talent/view?id="+resume_id, null);
    	}
    	catch(Exception e){
    		return CommonUtils.msgCallback(false, "操作失败，请重试！"+e.getMessage(), "", null);
    	}
    	
        //return "redirect:/oa/talent/view?id="+resume_id;
    }
    
    @RequestMapping(value = "/search", method = {RequestMethod.POST, RequestMethod.GET})
    public String search(String jobTitle, String companyName, Integer status, Long pageNo, Model model) {
        status = status == null || status < 0 ? null : status;       
        int pageIndex = pageNo!=null? pageNo.intValue():0;
       
        Pager<Talent> page = new Pager<>(pageIndex,20) ;
        
        TextCriteria criteria = TextCriteria.forDefaultLanguage().matching(jobTitle);

		Query query = TextQuery.queryText(criteria)
		  .sortByScore()
		  .with(new PageRequest(pageIndex, 20));
        
    	if(companyName!=null){
    		criteria.matching(companyName);
        }
    	else if(status!=null){
    		//query.addCriteria(criteriaDefinition)
        	
        }
    	
    	List<Talent> recipes= destination.find(query, Talent.class);
    	page.setItems(recipes);
        model.addAttribute("page", page);
        model.addAttribute("pageIndex",pageIndex);
        List<ArticleCategory> articleCategoryList = articleCategoryService.findListByParentId(talentCategoryId, 1);
        model.addAttribute("articleCategoryList", articleCategoryList);
        return THEME_PATH + "/oa/talent/list";
    }
}
